﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Reflection;

namespace SimpleRest.Core.Extensions.Routes
{
    public class XsdRouteHandler : IRouteHandler
    {
        public readonly Type TargetType;
        public readonly string TargetHttpMethod;

        /// <summary>
        /// The associated operation route that this XSD route handler is associated to.
        /// </summary>
        private readonly Route AssociatedRoute;
        public Pipeline RoutePipeline { get; private set; }
        public Configuration Configuration;

        protected XsdRouteHandler() { }
        public XsdRouteHandler(Pipeline routePipeline, string targetHttpVerb, Type targetType, Route associatedRoute, Configuration configuration)
            : base()
        {
            this.TargetType = targetType;
            this.AssociatedRoute = associatedRoute;
            this.TargetHttpMethod = targetHttpVerb;
            this.Configuration = configuration;
            this.RoutePipeline = routePipeline;
        }

        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            if (requestContext.HttpContext.Request.HttpMethod.ToLower().Equals(this.TargetHttpMethod.ToLower()))
            {
                return new XsdHttpHandler(this.RoutePipeline, TargetType, this.Configuration, requestContext);
            }
            else
            {
                // in the event that the request should not be routed to the operation xsd http handler then
                // reroute this request to the original operation route associated to this XSD route.
                return AssociatedRoute.RouteHandler.GetHttpHandler(requestContext);
            }
        }
    }
}
